package bin_tree.leetcode;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

/**
 * @author yuisama
 * @date 2023/03/27 19:29
 * 中序遍历
 **/
public class Num94_InOrder {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        TreeNode cur = root;
        Deque<TreeNode> stack = new ArrayDeque<>();
        while (cur != null || !stack.isEmpty()) {
            // 先不断的向左走到头儿~
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            // 此时cur== null，栈顶就存放了第一个要输出的结点
            // 当前栈顶就是第一个左树为空的结点
            cur = stack.pop();
            result.add(cur.val);
            // 继续访问右子树
            cur = cur.right;
        }
        return result;
    }
}